<template>
  <div>
    <!--  视频号名称  -->
    <TemplateText
      v-if="elementsKey.username"
      :ref="(el) => setItemRef(el, elementsKey.username.name)"
      :key="elementsKey.username.name"
      :loading="channelLoading"
      is-update
      is-channels
      :params="attributes[elementsKey.username.index]"
      @upload="handleFetchWechatChannelList"
      @change="handleWeChatChannelsChange"
    />
    <TemplateText
      v-else-if="channelsUserName"
      :ref="(el) => setItemRef(el, channelsUserName.name)"
      :key="channelsUserName.name"
      :loading="channelLoading"
      :params="channelsUserName"
      is-update
      is-channels
      @upload="handleFetchWechatChannelList"
    />
    <!--头像及昵称跳转页，复合版位的时候，有头像显示头像，没有头像看是否有品牌-->
    <template v-if="attributesKey.profile_id">
      <TemplateAvatar
        v-if="attributesKey.profile_id"
        :ref="(el) => setItemRef(el, attributesKey.profile_id.name)"
        :key="attributesKey.profile_id.name"
        :params="attributes[attributesKey.profile_id.index]"
      />
    </template>
    <!--品牌标识-->
    <TemplateBrand
      v-else-if="Brand"
      :ref="(el) => setItemRef(el, Brand.name)"
      :key="Brand.name"
      :params="elements[Brand.index]"
    />
    <!--用组件替换-->
    <!--动画效果-->
    <TemplateText
      v-if="elementsKey.animation_effect"
      :ref="(el) => setItemRef(el, elementsKey.animation_effect.name)"
      :key="elementsKey.animation_effect.name"
      :params="elements[elementsKey.animation_effect.index]"
    />
    <!--视频号视频-->
    <template v-if="shortVideoStruct">
      <TemplateMedia
        :ref="(el) => setItemRef(el, shortVideoStruct.short_video2)"
        :key="shortVideoStruct.short_video2.name"
        :params="shortVideoStruct.short_video2"
        @change="videoChange"
      />
    </template>
    <!--单图片-->
    <template v-if="elementsKey.image_list && elements[elementsKey.image_list.index].children.length === 1">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi v-if="elementsKey.image_list" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.image_list.name)"
            :params="elements[elementsKey.image_list.index].children[0]"
          />
        </n-gi>
      </n-grid>
    </template>
    <!--单图片、单视频-->
    <template v-if="elementsKey.video || elementsKey.image">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi v-if="elementsKey.video" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.video.name)"
            :key="elementsKey.video.name"
            :params="elements[elementsKey.video.index]"
            @change="videoChange"
          />
        </n-gi>
        <n-gi v-if="elementsKey.image" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.image.name)"
            :key="elementsKey.image.name"
            :params="elements[elementsKey.image.index]"
          />
        </n-gi>
      </n-grid>
    </template>
    <!--多图片-->
    <template v-if="elementsKey.element_story" :gutter="5" class="template-element_story">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi
          v-for="(item, index) in elements[elementsKey.element_story.index].children"
          :key="index"
          class="ad-template-group"
        >
          <!--图片-->
          <TemplateMedia
            v-if="item.image"
            :ref="(el) => setItemRef(el, item.image.name + index)"
            :key="item.image.name + index"
            :params="item.image"
          />
          <!--广告描述-->
          <TemplateText
            v-if="item.description"
            :ref="(el) => setItemRef(el, item.description.name + index)"
            :kye="item.description.name + index"
            :params="item.description"
          />
          <!--落地页-->
          <TemplateText
            v-if="item.url"
            :ref="(el) => setItemRef(el, item.url.name + index)"
            :key="item.url.name + index"
            :params="item.url"
          />
        </n-gi>
      </n-grid>
    </template>

    <!--多个媒体素材-->
    <n-grid v-if="fileList" x-gap="12" :cols="1" class="template-element_story">
      <n-gi v-for="(item, index) in elements[fileList.index].children" :key="index" class="ad-template-group">
        <!--图片-->
        <TemplateMedia
          v-if="Object.keys(item).length === 1"
          :ref="(el) => setItemRef(el, item.name + index)"
          :params="item[Object.keys(item)[0]]"
        />
        <TemplateMedia v-else :ref="(el) => setItemRef(el, item.name + index)" :params="item" />
      </n-gi>
    </n-grid>
    <!--链接页面类型-->
    <TemplateRadio
      v-if="attributesKey.self_support_page"
      :ref="(el) => setItemRef(el, attributesKey.self_support_page.name)"
      :key="attributesKey.self_support_page.name"
      :params="attributes[attributesKey.self_support_page.index]"
      :filter="self_support_page_filter"
      :default-value="self_support_page_default_value"
      @change="onChangePageType"
    />
    <!--原生推广页-->
    <template v-if="self_support_page === 'PAGE_TYPE_CANVAS_WECHAT'">
      <TemplateText
        v-if="attributesKey.canvas_page"
        :ref="(el) => setItemRef(el, attributesKey.canvas_page.name)"
        :key="attributesKey.canvas_page.name"
        :loading="upload_loading"
        :params="canvasPageList"
        is-update
        @upload="handleUploadCanvas"
      />
    </template>
    <TemplateText
      v-if="attributesKey.link_name_type"
      :ref="(el) => setItemRef(el, attributesKey.link_name_type.name)"
      :key="attributesKey.link_name_type.name"
      :params="attributes[attributesKey.link_name_type.index]"
    />
    <!--广告文案-->
    <TemplateText
      v-if="elementsKey.title"
      :ref="(el) => setItemRef(el, elementsKey.title.name)"
      :key="elementsKey.title.name"
      :params="elements[elementsKey.title.index]"
    />
    <!--广告描述-->
    <TemplateText
      v-if="elementsKey.description"
      :ref="(el) => setItemRef(el, elementsKey.description.name)"
      :key="elementsKey.description.name"
      :params="elements[elementsKey.description.index]"
      :textarea="isTextarea"
    />
    <!--投放页面类型-->
    <TemplatePage
      v-if="landing_page_config"
      :ref="(el) => setItemRef(el, landing_page_config.support_page_type_list[0]?.page_type)"
      :key="landing_page_config"
      :params="landing_page_config"
    />
    <!--商品标签-->
    <TemplateText
      v-if="elementsKey.product_tags"
      :ref="(el) => setItemRef(el, elementsKey.product_tags.name)"
      :key="elementsKey.product_tags.name"
      :params="elements[elementsKey.product_tags.index]"
    />
    <!--按钮文案-->
    <TemplateText
      v-if="elementsKey.button_text"
      :ref="(el) => setItemRef(el, elementsKey.button_text.name)"
      :key="elementsKey.button_text.name"
      :params="elements[elementsKey.button_text.index]"
      @change="onChangeLinkType"
    />
    <!--行动按钮-->
    <TemplateText
      v-if="attributesKey.button_text"
      :ref="(el) => setItemRef(el, attributesKey.button_text.name)"
      :key="attributesKey.button_text.name"
      :params="attributes[attributesKey.button_text.index]"
      @change="onChangeLinkType"
    />
    <!--数据展示-->
    <TemplateRadio
      v-if="attributesKey.conversion_data_type"
      :ref="(el) => setItemRef(el, attributesKey.conversion_data_type.name)"
      :key="attributesKey.conversion_data_type.name"
      :params="attributes[attributesKey.conversion_data_type.index]"
    />
    <template v-if="isConversionTargetType">
      <TemplateRadio
        v-if="attributesKey.conversion_target_type"
        :ref="(el) => setItemRef(el, attributesKey.conversion_target_type.name)"
        :key="attributesKey.conversion_target_type.name"
        :params="attributes[attributesKey.conversion_target_type.index]"
        :retain="conversion_target_list"
      />
    </template>
    <TemplateText
      v-if="attributesKey.share_title"
      :ref="(el) => setItemRef(el, attributesKey.share_title.name)"
      :key="attributesKey.share_title.name"
      :params="attributes[attributesKey.share_title.index]"
      required
    />
    <TemplateText
      v-if="attributesKey.share_description"
      :ref="(el) => setItemRef(el, attributesKey.share_description.name)"
      :key="attributesKey.share_description.name"
      :params="attributes[attributesKey.share_description.index]"
      required
    />
    <!--左下辅助文案-->
    <TemplateText
      v-if="elementsKey.bottom_text"
      :ref="(el) => setItemRef(el, elementsKey.bottom_text.name)"
      :key="elementsKey.bottom_text.name"
      :params="elements[elementsKey.bottom_text.index]"
    />
    <!--次行文案-->
    <TemplateText
      v-if="elementsKey.caption"
      :ref="(el) => setItemRef(el, elementsKey.caption.name)"
      :key="elementsKey.caption.name"
      :params="elements[elementsKey.caption.index]"
    />
    <!--第三行文案-->
    <TemplateText
      v-if="elementsKey.left_bottom_txt"
      :ref="(el) => setItemRef(el, elementsKey.left_bottom_txt.name)"
      :key="elementsKey.left_bottom_txt.name"
      :params="elements[elementsKey.left_bottom_txt.index]"
    />
    <!--复选框-->
    <TemplateCheckbox
      v-if="attributesKey.multi_share_optimization_enabled"
      :ref="(el) => setItemRef(el, attributesKey.multi_share_optimization_enabled.name)"
      :key="attributesKey.multi_share_optimization_enabled.name"
      :params="attributes[attributesKey.multi_share_optimization_enabled.index]"
    />
    <!--标签-->
    <TemplateLabel
      v-if="elementsKey.label"
      :ref="(el) => setItemRef(el, elementsKey.label.name)"
      :key="elementsKey.label.name"
      :params="elements[elementsKey.label.index]"
    />

    <!--自动衍生视频创意-->
    <TemplateRadio
      v-if="elementsKey.auto_derived_creative_enabled"
      :ref="(el) => setItemRef(el, elementsKey.auto_derived_creative_enabled.name)"
      :key="elementsKey.auto_derived_creative_enabled.name"
      :params="attributes[elementsKey.auto_derived_creative_enabled.index]"
      is-switch
    />

    <!--视频号浮层卡片-->
    <!--TemplateMedia ref报警告-->
    <template v-if="floatingZoneStruct && siteSet.includes('SITE_SET_CHANNELS')">
      <!--      <TemplateMedia-->
      <!--        :ref="(el) => setItemRef(el, floatingZoneStruct.image_id)"-->
      <!--        :key="floatingZoneStruct.image_id.name"-->
      <!--        :params="floatingZoneStruct.image_id"-->
      <!--      />-->
      <!--确保唯一值 加了uuid-->
      <TemplateMedia
        :ref="(el) => setItemRef(el, floatingZoneStruct.image_id + uuid)"
        :key="floatingZoneStruct.image_id.name"
        :params="floatingZoneStruct.image_id"
      />
      <TemplateText
        v-if="floatingZoneStruct.name"
        :ref="(el) => setItemRef(el, floatingZoneStruct.name.name)"
        :key="floatingZoneStruct.name.name"
        :params="floatingZoneStruct.name"
      />
      <TemplateText
        v-if="floatingZoneStruct.desc"
        :ref="(el) => setItemRef(el, floatingZoneStruct.desc.name)"
        :key="floatingZoneStruct.desc.name"
        :params="floatingZoneStruct.desc"
      />
      <TemplateText
        v-if="floatingZoneStruct.button_text"
        :ref="(el) => setItemRef(el, floatingZoneStruct.button_text.name)"
        :key="floatingZoneStruct.button_text.name"
        :params="floatingZoneStruct.button_text"
      />
    </template>
    <!--    &lt;!&ndash;是否保存至视频号&ndash;&gt;-->
    <!--    <TemplateRadio-->
    <!--      v-if="elementsKey.finder_object_visibility"-->
    <!--      :ref="(el) => setItemRef(el, elementsKey.finder_object_visibility.name)"-->
    <!--      :key="elementsKey.finder_object_visibility.name"-->
    <!--      :params="elements[elementsKey.finder_object_visibility.index]"-->
    <!--      is-switch-->
    <!--    />-->
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router'
  const route = useRoute()
  import { computed, onMounted, reactive, ref } from 'vue'
  import { useStore } from '@/store'
  import { NGrid, NGi } from 'naive-ui'
  import TemplateText from '@/views/advertising/ads/create/components/step7/TemplateText.vue'
  import TemplateMedia from '@/views/advertising/ads/create/components/step7/TemplateMedia.vue'
  import TemplateAvatar from '@/views/advertising/ads/create/components/step7/TemplateAvatar.vue'
  import TemplateRadio from '@/views/advertising/ads/create/components/step7/TemplateRadio.vue'
  import TemplateCheckbox from '@/views/advertising/ads/create/components/step7/TemplateCheckbox.vue'
  import TemplateLabel from '@/views/advertising/ads/create/components/step7/TemplateLabel.vue'
  import TemplateBrand from '@/views/advertising/ads/create/components/step7/TemplateBrand.vue'
  import TemplatePage from '@/views/advertising/ads/create/components/step7/TemplatePage.vue'

  const store = useStore()
  const props = defineProps({
    detail: {
      type: Object,
      default: () => ({})
    }
  })
  const getProps = reactive(props)
  const isEdit = computed(() => {
    return !!store.state.intelligent.data.id
  })
  const creative = computed(() => {
    return store.state.intelligent.data.creative
  })
  const position = computed(() => {
    return store.state.intelligent.data.position
  })
  const siteSet = computed(() => {
    return store.state.intelligent.data.position.siteSet
  })
  const attributes = computed(() => {
    return getProps.detail ? getProps.detail.adcreative_attributes : []
  })
  const attributesKey = computed(() => {
    const keys = {}
    attributes.value.forEach((item, index) => {
      keys[item.name] = {
        index,
        name: item.name
      }
    })
    return keys
  })
  const elements = computed(() => {
    return getProps.detail ? getProps.detail.adcreative_elements : []
  })
  const elementsKey = computed(() => {
    const keys = {}
    elements.value.forEach((item, index) => {
      keys[item.name] = {
        index,
        name: item.name
      }
    })
    // console.log(keys)
    return keys
  })
  // 品牌标识
  const Brand = computed(() => {
    return elementsKey.value.brand || elementsKey.value.corporate
  })
  const landing_page_config = computed(() => {
    return getProps.detail.landing_page_config
  })
  const channelsUserName = computed(() => {
    if (elementsKey.value.wechat_channels_spec) {
      return elements.value[elementsKey.value.wechat_channels_spec.index].children.username
    } else {
      return null
    }
  })

  const floatingZoneStruct = computed(() => {
    return elementsKey.value.floating_zone_struct
      ? elements.value[elementsKey.value.floating_zone_struct.index].children
      : null
  })
  const shortVideoStruct = computed(() => {
    return elementsKey.value.short_video_struct
      ? elements.value[elementsKey.value.short_video_struct.index].children
      : null
  })
  const fileList = computed(() => {
    const list =
      elementsKey.value.image_list || elementsKey.value.short_video_struct_options || elementsKey.value.video_options
    if (list && elements.value[list.index].children.length > 1) {
      return list
    } else {
      return false
    }
  })
  const canvasPageList = computed(() => {
    if (attributesKey.value.canvas_page) {
      const params = attributes.value[attributesKey.value.canvas_page.index]
      const enumeration = params.enum_property.enumeration || []
      params.enum_property.enumeration = enumeration.map((item) => {
        let page_elements_spec_list = item.page_elements_spec_list || []
        if (page_elements_spec_list && typeof page_elements_spec_list === 'string') {
          page_elements_spec_list = JSON.parse(page_elements_spec_list)
        }
        return {
          ...item,
          page_elements_spec_list
        }
      })
      return params
    } else {
      return []
    }
  })
  const isConversionTargetType = computed(() => {
    return (
      attributesKey.value.conversion_data_type &&
      attributes.value[attributesKey.value.conversion_data_type.index].default
    )
  })
  const computedSiteSet = computed(() => {
    return position.value.siteSetType ? creative.value.siteSet : siteSet.value
  })
  const isTextarea = computed(() => {
    return [263, 310, 311, 618, 641, 642, 643, 644, 645, 646, 647, 648, 649, 721, 1064, 1465, 1480].some(
      (item) => item === creative.value.templateId
    )
  })
  const accountCode = computed(() => {
    return store.state.intelligent.data.accountCode
  })
  const mediaPreset = ref({})
  const modalData = ref({
    show: false
  })
  function handleMediaSelect() {
    modalData.value.show = true
  }
  const landing_page_type = ref()
  const upload_loading = ref(false)
  const channelLoading = ref(false)
  const self_support_page = ref()
  const self_support_page_default_value = ref()
  const self_support_page_filter = ref()
  const conversion_target_list = ref()
  const channelsId = ref('')
  const grabValue = ref('')

  const itemRefs = {}
  const setItemRef = (el: any, key) => {
    if (el) {
      itemRefs[key] = el
    }
  }

  onMounted(() => {
    // console.log('detail => ', getProps.detail)
  })

  async function validate() {
    // 如果没有数据展示转换行为 删除指向的ref
    if (!isConversionTargetType.value) {
      try {
        delete itemRefs[attributesKey.value.conversion_target_type.name]
      } catch (e) {}
    }
    return new Promise(async (resolve, reject) => {
      // const refs = this.$refs || []
      const refs = itemRefs || []
      let is = true
      for (const key in refs) {
        let ref = refs[key]
        if (Object.prototype.toString.call(refs[key]) === '[object Array]') {
          ref = ref[0]
        }
        // 校验不通过，跳出循环
        if (ref && !(await ref.validate())) {
          is = false
          break
        }
      }
      resolve(is)
    })
  }
  // 链接页面类型
  function onChangePageType(val, type) {
    self_support_page.value = val
  }
  // 更新原生推广页可选择数据
  function onCanvasPageUpdate(refresh = 0) {
    upload_loading.value = true
    store
      .dispatch('intelligent/getAdsCanvasPage', {
        refresh,
        accountCode: accountCode.value,
        templateId: creative.value.templateId,
        siteSets: position.value.siteSet.join(',')
      })
      .then((res) => {
        upload_loading.value = false
        const params = attributes.value[attributesKey.value.canvas_page.index]
        params.enum_property.enumeration = res.data
      })
      .catch(() => {
        upload_loading.value = false
      })
  }
  // 主动获取原生推广页
  function handleUploadCanvas() {
    // 主动强制获取原生推广页数据
    onCanvasPageUpdate(1)
  }
  function onChangeLinkType(val, options, m) {
    try {
      const find = attributes.value[attributesKey.value.conversion_target_type.index]
      conversion_target_list.value = options.conversion_target_list || []
      if (['WATCH_LIVE'].includes(val)) {
        // 观看直播的不支持 数据展示数据类型
        attributes.value[attributesKey.value.conversion_data_type.index].default = false
        conversion_target_list.value = []
        find.default = null
      } else {
        if (isConversionTargetType.value && conversion_target_list.value.length) {
          find.default = conversion_target_list.value[0].value
        } else {
          if (!isEdit.value) {
            find.default = null
          }
        }
      }
      // console.log(isShow);
    } catch (e) {
      console.warn('attributesKey.conversion_target_type 不存在')
    }
  }
  function handleFetchWechatChannelList() {
    channelLoading.value = true
    store
      .dispatch('intelligent/getAdsWechatChannel', {
        accountCode: accountCode.value
      })
      .then((res) => {
        channelLoading.value = false
        const params = elementsKey.value.username
          ? attributes.value[elementsKey.value.username.index]
          : channelsUserName.value
        params.enum_property.enumeration = res.data
      })
      .catch(() => {
        channelLoading.value = false
      })
  }
  function handleWeChatChannelsChange(value, item) {
    channelsId.value = value
    grabValue.value = item ? item.grabValue : ''
  }
  // 视频上传自动使用首帧作为封面图
  function videoChange(val) {
    if (elementsKey.value.image) {
      const params = elements.value[elementsKey.value.image.index]
      store
        .dispatch('intelligent/mediaUpload', {
          accountCode: accountCode.value,
          keyFrameImageUrl: val.keyFrameImageUrl,
          fileType: '1'
        })
        .then((res: any) => {
          params.default = res.data.mediaId
          params.file = res.data.previewUrl
          params.fileUrl = res.data.previewUrl
        })
    }
  }

  defineExpose({
    validate
  })
</script>

<style scoped lang="scss"></style>
